const fs = require('fs');
const path = require('path');

class Controller{
  constructor(app,res,req){
    this.app = app;
    this.res = res;
    this.req = req;
  }
}
exports.Controller= Controller;

const loadController = controllerpath =>{
  const controllmap=  {}
  const files = fs.readdirSync(controllerpath)
  files.forEach(file => {
    const fileState = fs.statSync(path.join(controllerpath,file))
    if(fileState.isFile()){
      const controllName = file.substr(0,file.lastIndexOf('.'))
      if(controllName){
        controllmap[controllerpath]={
          isDir: false,
          value: require(path.join(controllerpath,file))
        }
      }
   
    }else{
      controllmap[file] = {
        isDir: true,
        ...loadController(path.join(controllerpath,file))
      }
    }
  })
  return controllmap
}
const errMsg = message => ({ code: 1, message, data: null })
const createProxy =(controllmap,app)=>{
  return new Proxy(controllmap,{
    get(target,key){
      if(target[key]){
        if(!target[key].isDir){
          return new Proxy(target[key]),{
            get(target,key){
              return(req,res)=>{
                if(Object.getOwnPropertyNames(target[key].value).includes(key)){
                  new target.value(req,res,app)[name]()
                }else{
                  res.send(errMsg('method not exist'))
                }
              }
            }
          }
        }
      }else{
       return new Proxy({},{
        get() {
          return (req, res) => {
            res.send(errMsg('controller not exist'))
          }
        }
       })
      }
    }
  })
}

const controllerMap =loadController(path.join(__dirname,'../controller'))
module.exports= app=>{
  app.controller = createProxy(controllerMap,app)
  return(req,res,next)=>{
    next()
  }
}